<route lang="json5">
{
  needLogin: true,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '选择成员',
  },
}
</route>
<template>
  <view class="page-container bg-[#f5f5f5]">
    <!-- 顶部导航栏 -->
    <wd-navbar
      title="选择成员"
      left-arrow
      placeholder
      @click-left="goBack"
      custom-style="background: #fff; border-bottom: none;"
      fixed
      safeAreaInsetTop
    >
      <template #right>
        <wd-button size="small" :round="false" custom-class="custom-success" @click="handleSubmit">
          移除
        </wd-button>
      </template>
    </wd-navbar>
    <!-- 顶部搜索区域 -->
    <view class="bg-white px-30rpx py-12rpx w-full box-border">
      <view class="flex">
        <view class="member-selects">
          <view
            v-for="member in selectedMembers"
            :key="member.studentId"
            @click="toggleMember(member)"
          >
            <view v-if="!member.headshot" class="avatar-placeholder flex-center">
              {{ getLastTwoChars(member.name) }}
            </view>
            <image v-else :src="member.headshot" class="student-avatar" mode="aspectFill" />
          </view>
        </view>
        <view class="flex-1 h-82rpx">
          <wd-input
            type="text"
            v-model="keyword"
            no-border
            placeholder="搜索"
            @change="handleSearch"
            custom-class="member-search"
          />
        </view>
      </view>
    </view>

    <!-- 班级列表 -->
    <scroll-view scroll-y class="class-scroll-view">
      <!-- 学生列表区域 -->
      <view class="student-list-container">
        <wd-index-bar highlight-color="#3670F7">
          <template v-for="letterGroup in groupedClassGroups" :key="letterGroup.letter">
            <!-- 字母索引锚点 -->
            <wd-index-anchor :index="letterGroup.letter">
              {{ letterGroup.letter }}
            </wd-index-anchor>

            <!-- 学生列表 -->
            <view class="student-list">
              <view
                v-for="student in letterGroup.students"
                :key="student.studentId"
                class="student-item"
                @click="toggleMember(student)"
              >
                <view class="flex items-center">
                  <wd-checkbox
                    :modelValue="selectedMembers.some((m) => m.studentId === student.studentId)"
                    custom-class="checkbox-style"
                  ></wd-checkbox>
                  <view v-if="!student.headshot" class="avatar-placeholder flex-center">
                    {{ getLastTwoChars(student.name) }}
                  </view>
                  <image v-else :src="student.headshot" class="student-avatar" mode="aspectFill" />
                  <text class="student-name">{{ student.name }}</text>
                </view>
              </view>
            </view>
          </template>
        </wd-index-bar>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type {
  ClassGroup,
  IndexedStudent,
  GroupedClassGroup,
  LetterGroup,
  Student,
} from '@/types/edu'
import pinyin from 'pinyin' // 处理拼音工具
import { inviteGroup, kickGroup, membersGroupInfo } from '@/service/edu/group'
import { getStudentList } from '@/service/edu/lesson/lessonMain'
import { useGroupStore, useUserStore } from '@/store'
const searchWidth = ref('30%')
const selectedMembers = ref<IndexedStudent[]>([])
const searchText = ref('')
const keyword = ref('')
const groupInfo = ref({
  create: '',
  id: '',
  groupId: '',
  showGroupName: '',
  headImageThumb: '',
})

function goBack() {
  uni.navigateBack()
}
function handleSearch() {}
// 数据
const classGroups = ref<Student[]>([])
const userStore = useUserStore()
const handleMemberInfo = (groupId) => {
  membersGroupInfo(groupId).then((group) => {
    if (group.code === 200) {
      let list = group.data
      if (list && list.length > 0) {
        list.forEach((item) => {
          item.name = item?.showNickName
          item.studentId = item?.userId
          item.headshot = item?.headImage
        })
        list = list.filter((item) => item.userId !== userStore.userInfo.userId)
      }
      classGroups.value = list
    }
  })
}
function getChineseFirstLetter(chinese: string) {
  // 获取第一个汉字
  const firstChar = chinese.charAt(0)
  // 使用 pinyin 转换为拼音
  const pinyinResult = pinyin(firstChar, {
    style: pinyin.STYLE_NORMAL,
  })
  // 获取拼音首字母并转大写
  return pinyinResult[0][0].charAt(0).toUpperCase()
}
// 获取姓名的最后两个字
function getLastTwoChars(name: string) {
  if (name && name.length > 0) {
    return name.slice(-2)
  }
  return name
}
// 处理数据，按班级和字母分组
const groupedClassGroups = computed(() => {
  const LetterGroup = []
  classGroups.value.forEach((group: any) => {
    group.letter = getChineseFirstLetter(group.name)
  })
  const letterGroups = classGroups.value.reduce((groups: LetterGroup[], student: any) => {
    const existingGroup = groups.find((g) => g.letter === student.letter)
    if (existingGroup) {
      existingGroup.students.push(student)
    } else {
      groups.push({
        letter: student.letter,
        students: [student],
      })
    }
    return groups
  }, [])
  // 对字母组进行排序
  letterGroups.sort((a, b) => a.letter.localeCompare(b.letter))
  // 对每个字母组内的学生按姓名排序
  letterGroups.forEach((group) => {
    group.students.sort((a, b) => a.name.localeCompare(b.name))
  })
  return letterGroups
})

// 选择/取消选择成员
const toggleMember = (student: IndexedStudent) => {
  const index = selectedMembers.value.findIndex((m) => m.studentId === student.studentId)
  if (index === -1) {
    selectedMembers.value.push(student)
  } else {
    selectedMembers.value.splice(index, 1)
  }
}
const groupStore = useGroupStore()
onLoad(async () => {
  const pages = getCurrentPages()
  const currentPage: any = pages[pages.length - 1]
  const query = currentPage.$page?.options || currentPage?.options || currentPage.$route.query
  if (query) {
    groupInfo.value.groupId = query.groupId
    if (query.groupId) {
      handleMemberInfo(query.groupId)
    }
    if (query.create) {
      groupInfo.value.create = query.create
    }
    if (groupStore.createType) {
      classGroups.value = groupStore.createFriendIds
    }
  }
})
// 处理完成按钮点击
function handleSubmit() {
  console.log('classGroups.value======', classGroups.value)
  console.log('selectedMembers.value======', selectedMembers.value)
  // const studentIds = selectedMembers.value.map((item) => item.studentId)
  uni.showModal({
    title: '提示',
    content: `是否确认移除已选择的${selectedMembers.value.length}位成员？`,
    success: async (res) => {
      try {
        if (res.confirm) {
          if (groupInfo.value.create === '1') {
            const filteredStudents = classGroups.value.filter((student) => {
              return !selectedMembers.value.some((toBeFilteredStudent) => {
                return toBeFilteredStudent.studentId === student.studentId
              })
            })
            groupStore.setFriendIds(filteredStudents)
            groupStore.setCreateType(true)
            uni.navigateBack()
          } else {
            groupStore.setCreateType(false)
            groupStore.setFriendIds([])
            kickGroup({
              groupId: groupInfo.value.groupId,
              userIds: selectedMembers.value.map((item) => item.studentId),
            }).then((data) => {
              if (data.code === 200) {
                uni.navigateBack()
              }
            })
          }
        }
      } catch (e) {
        console.error('删除失败', e)
      } finally {
        console.log('请求')
      }
    },
  })
}
</script>
<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
}

.fixed-top {
  position: fixed;
  top: var(--window-top);
  right: 0;
  left: 0;
  z-index: 99;
}

.member-tag {
  font-size: 26rpx;
}

.student-avatar,
.avatar-placeholder {
  width: 82rpx;
  height: 82rpx;
  margin-right: 16rpx;
  border-radius: 12rpx;
}

.avatar-placeholder {
  font-size: 28rpx;
  color: #fff;
  background-color: #3670f7;
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.class-title {
  padding: 20rpx 32rpx;
  font-size: 30rpx;
  font-weight: 500;
  background-color: #f5f5f5;
}

.student-list {
  background-color: #fff;
}

.student-item {
  padding: 24rpx 32rpx;
  border-bottom: 1px solid #f5f5f5;
}
.student-item:last-child {
  border-bottom: none;
}

.student-name {
  margin-left: 24rpx;
  font-size: 26rpx;
  color: #333;
}

.checkbox-style {
  width: 46rpx !important;
  height: 46rpx !important;
  margin-right: 24rpx;
}
:deep(.wd-checkbox__shape) {
  width: 46rpx !important;
  height: 46rpx !important;
}

:deep(.wd-index-anchor) {
  height: 48rpx;
  padding: 12rpx 32rpx;
  font-size: 24rpx;
  line-height: 48rpx;
  color: #666;
  background-color: #f5f5f5;
}

:deep(.wd-index-bar__sidebar) {
  right: 0;
}

.class-scroll-view {
  height: calc(100vh - 180rpx);
  background-color: #fff;
}

.class-item {
  padding: 12rpx 32rpx;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.class-content {
  display: flex;
  align-items: center;
  padding: 12rpx 8rpx;
  font-weight: bold;
  border-bottom: 1rpx solid #edf2fa;
}

.class-name {
  margin-right: 12rpx;
  font-size: 30rpx;
  color: #1a1a1a;
}

.student-count {
  font-size: 30rpx;
  color: #1a1a1a;
}

.student-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.popup-header {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.popup-title {
  flex: 1;
  margin-left: -40rpx; /* 抵消返回按钮的宽度，使标题居中 */
  font-size: 34rpx;
  font-weight: 500;
  text-align: center;
}

.header-right {
  min-width: 40rpx;
}

.done-text {
  font-size: 28rpx;
  color: #3670f7;
}

.student-list-container {
  flex: 1;
  overflow-y: auto;
}

.member-search {
  height: 82rpx !important;
  margin-left: 8rpx;
  font-size: 36rpx !important;
  color: #b2b5bd;
}
:deep(.wd-input.is-no-border .wd-input__inner) {
  height: 82rpx !important;
}
.member-selects {
  display: flex;
  max-width: 80%;
  overflow-y: auto;
}
</style>
